package com.fenrirtec.aepp.common.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fenrirtec.aepp.common.dao.CodeNameDao;
import com.fenrirtec.aepp.common.model.CodeName;
import com.fenrirtec.core.database.DatabaseSessionManager;
import com.fenrirtec.core.database.ResultSetMapper;
import com.fenrirtec.core.exception.DatabaseException;

public class CodeNameDao_JDBCImpl implements CodeNameDao {

	private static final Logger logger = LoggerFactory.getLogger(CodeNameDao_JDBCImpl.class);

	@Override
	public List<CodeName> findByTypeId(String typeId) {
		if (logger.isInfoEnabled()) {
			logger.info("[CodeNameDao_JDBCImpl#findAll] start.");
		}

		PreparedStatement statement = null;
		try {
			StringBuilder sql = new StringBuilder()
				.append("select \n")
				.append("  type_id, \n")
				.append("  code, \n")
				.append("  name, \n")
				.append("  create_user, \n")
				.append("  create_date, \n")
				.append("  update_user, \n")
				.append("  update_date, \n")
				.append("  delete_flag \n")
				.append("from \n")
				.append("  m_code_name \n")
				.append("where \n")
				.append("  type_id = ? \n")
				.append("and \n")
				.append("  delete_flag = false \n")
				.append("order by \n")
				.append("  code \n");
			if (logger.isTraceEnabled()) {
				logger.trace("[CodeNameDao_JDBCImpl#findAll] sql={}", sql);
			}
			Connection connection = DatabaseSessionManager.getInstance().getSession();
			statement = connection.prepareStatement(sql.toString());
			statement.setString(1, typeId);
			ResultSet resultSet = statement.executeQuery();
			
			ResultSetMapper<CodeName> resultSetMapper = new ResultSetMapper<CodeName>();
			List<CodeName> codeNames = resultSetMapper.mapResultSetToList(resultSet, CodeName.class);
			
			return codeNames;
		} catch (SQLException e) {
			if (logger.isTraceEnabled()) {
				logger.trace("[CodeNameDao_JDBCImpl#findAll] sql error occurred.", e);
			}
			throw new DatabaseException("database error occurred.", e);
		} finally {
			if (logger.isInfoEnabled()) {
				logger.info("[CodeNameDao_JDBCImpl#findAll] finish.");
			}
			if (statement != null) { try { statement.close(); } catch (SQLException e) {} }
		}
	}
}
